﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using Entity;

namespace DataAccess
{
    public class BranchClassTree
    {
        SqlDataAdapter daBranch;
        SqlDataAdapter daClass;
        GroupUserDA gDA = new GroupUserDA();
        public TreeNode getBranchClass(Account acc)
        {
            using (SqlConnection conn = Connect.getConnection())
            {
                try
                {

                    conn.Open();
                    DataSet ds = new DataSet();
                    TreeNode tn = new TreeNode();
                    string gName = gDA.getGroupNameByAccount(acc);
                    tn.Name = "root";
                    tn.Text = acc.name + " ("+gName+")";
                    daBranch = new SqlDataAdapter("getBranchByUserAccount", conn);
                    daBranch.SelectCommand.CommandType = CommandType.StoredProcedure;
                    daBranch.SelectCommand.Parameters.Add(new SqlParameter("@userID", acc.accountID));
                    daClass = new SqlDataAdapter("getClassByUserAccount", conn);
                    daClass.SelectCommand.CommandType = CommandType.StoredProcedure;
                    daClass.SelectCommand.Parameters.Add(new SqlParameter("@userID", acc.accountID));
                    daBranch.Fill(ds,"br");
                    daClass.Fill(ds,"cl");
                    ds.Relations.Add("br_cl", ds.Tables["br"].Columns["BranchID"], ds.Tables["cl"].Columns["BranchID"]);
                    foreach (DataRow row in ds.Tables["br"].Rows)
                    {
                        TreeNode nod = new TreeNode(row["BranchName"].ToString(),1,3);
                        foreach (DataRow rowChild in row.GetChildRows("br_cl"))
                        {
                            TreeNode nodChild = new TreeNode(rowChild["ClassName"].ToString(),2,4);
                            nod.Nodes.Add(nodChild);
                        }
                        tn.Nodes.Add(nod);
                    }
                    conn.Close();
                    return tn;
                }
                catch (Exception)
                {
                    conn.Close();
                    return null;
                }
            }
        }
    }
}
